package work.comeback.omo.util.configuration.model;

import lombok.Getter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import work.comeback.omo.util.configuration.interfaces.ConfigParser;
import work.comeback.omo.util.configuration.service.ReflectiveConfigParser;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@Getter
public class AppConfig {

    private static final Logger logger = LoggerFactory.getLogger(AppConfig.class);
    private final Properties properties = new Properties();
    private final ConfigOptions configOptions = new ConfigOptions();

    public AppConfig() {
        this("application.properties");
    }

    public AppConfig(String configFile) {
        this.readConfig(configFile);
    }

    public AppConfig(String ...files) {
        readConfigList(files);
    }

    private void readConfigList(String ...files) {
        for (String file : files) {
            readConfig(file);
        }
    }

    private void readConfig(String configFile) {
        ClassLoader classLoader = getClass().getClassLoader();

        try (InputStream is = classLoader.getResourceAsStream(configFile)) {
            if (is == null) {
                throw new IllegalArgumentException("Configuration file not found: " + configFile);
            }

            properties.load(is);
            // reflect - read config.
            ConfigParser parser = new ReflectiveConfigParser();
            // reflect - parser
            parser.parse(properties, configOptions);
        } catch (IOException e) {
            catchError(e);
        }
    }

    private void catchError(Exception err) {
        logger.error("Read config error: {}", err.getMessage());
        System.exit(1);
    }
}
